<template>
    <div class="city">
<van-index-bar :index-list="indexList">
<div v-for="(item,index) in cityList" :key="index">
    <van-index-anchor :index="item.index" />
    <van-cell v-for="(item,index) in item.list" :title="item.name" :key="index" @click="handleClick(item)"/>

</div>              
</van-index-bar>
    </div>
</template>

<script>
import Vue from 'vue';
import { IndexBar, IndexAnchor,Cell } from 'vant';
import instance from '@/utils/http'
import {mapMutations} from 'vuex'

Vue.use(IndexBar);
Vue.use(IndexAnchor);
Vue.use(Cell)
export default {
    data(){
        return{
            cityList:[
                {
                    index:"A",
                    list:['a1','a2']
                },
                {
                    index:'B',
                    list:['b1','b2','b3']
                }
            ],
                 indexList: [],
        }
    }, 
     created(){
        instance("/gateway?k=6077446",{
            headers:{
                'X-Host': 'mall.film-ticket.city.list'
            }
        }).then(res=>{
            console.log(res.data.data.cities)
            this.dataFilter(res.data.data.cities)
        })
    },
    methods:{
        ...mapMutations('city',['setCityName','setCityId']),
        dataFilter(cities){
            var letarr=[]
            for(var i =65;i<91;i++){
                letarr.push(String.fromCharCode(i))
            }
            //filter遍历26个字母，跟cities数据里的pinyin首字母大写进行遍历
            var cityArr=[]
            for(var j=0;j<letarr.length;j++){
                let tempArr= cities.filter(item=>item.pinyin.substring(0,1).toUpperCase()===letarr[j])
                if(tempArr.length>0){
                    cityArr.push({
                        index:letarr[j],
                        list:tempArr
                    })
                     this.indexList.push(letarr[j])
                }
            }   
            this.cityList=cityArr

        },
        handleClick(item){
            this.setCityName(item.name)
            this.setCityId(item.cityId)
            this.$router.back()
        }   

    }
}
</script>

<style scoped>

</style>